<template>
  <div class="min-h-screen bg-gray-50 p-4 lg:p-6">
    <LazyAdminNavBar />
    <!-- 主内容区域 -->
    <div class="bg-white rounded-lg shadow overflow-hidden">
      <!-- 标题和操作按钮 -->
      <div class="p-4 border-b border-gray-200 flex flex-col lg:flex-row justify-between items-start lg:items-center">
        <h1 class="text-2xl font-bold text-gray-800 mb-2 lg:mb-0">用户管理</h1>
        <div class="flex space-x-2 w-full lg:w-auto">
          <div class="relative flex-grow lg:flex-grow-0 lg:w-64">
            <input v-model="searchQuery" type="text" placeholder="搜索用户..."
              class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
            <svg class="absolute left-3 top-2.5 h-5 w-5 text-gray-400" fill="none" stroke="currentColor"
              viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
            </svg>
          </div>
          <button @click="openAddModal"
            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors whitespace-nowrap">
            添加用户
          </button>
        </div>
      </div>

      <!-- 用户表格 -->
      <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">用户ID</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">用户名</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">角色</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="(user, index) in users" :key="user.user_id">
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="flex items-center">
                  <div class="flex-shrink-0 h-10 w-10 rounded-full bg-blue-100 flex items-center justify-center">
                    <span class="text-blue-600 font-medium">{{ index + 1 }}</span>
                  </div>
                  <div class="ml-4">
                    <!-- <div class="text-sm font-medium text-gray-900">{{ user.username }}</div> -->
                    <div class="text-sm text-gray-500">ID: {{ user.user_id }}</div>
                  </div>
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ user.username }}</td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span :class="roleClass(user.role_id)">
                  {{ roleNames[user.role_id] || '普通用户' }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span :class="statusClass(user.disable)">
                  {{ user.disable == 0 ? '激活' : '禁用' }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <button @click="openEditModal(user)" class="text-blue-600 hover:text-blue-900 mr-3">编辑</button>
                <button @click="confirmDelete(user)" class="text-red-600 hover:text-red-900">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <!-- 分页 -->
      <div class="px-4 py-3 bg-gray-50 border-t border-gray-200 flex items-center justify-between">
        <div class="text-sm text-gray-700">
          显示 <span class="font-medium">{{ pagination?.perPage }}</span> 条，共 <span class="font-medium">{{
            pagination?.total || 0
            }}</span> 条
        </div>
        <div class="flex space-x-2">
          <button @click="prevPage" :disabled="currentPage === 1"
            :class="`px-3 py-1 border rounded-md text-sm font-medium ${currentPage === 1 ? 'text-gray-400 bg-gray-100 cursor-not-allowed' : 'text-gray-700 bg-white hover:bg-gray-50'}`">
            上一页
          </button>
          <button @click="nextPage" :disabled="currentPage * itemsPerPage >= pagination?.total"
            :class="`px-3 py-1 border rounded-md text-sm font-medium ${currentPage * itemsPerPage >= pagination?.total ? 'text-gray-400 bg-gray-100 cursor-not-allowed' : 'text-white bg-blue-600 hover:bg-blue-700'}`">
            下一页
          </button>
        </div>
      </div>
    </div>

    <!-- 添加/编辑用户模态框 -->
    <div v-if="showModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-md">
        <div class="p-6">
          <h2 class="text-xl font-semibold mb-4">{{ isEditing ? '编辑用户' : '添加用户' }}</h2>

          <form @submit.prevent="submitForm">
            <div class="space-y-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                <input v-model="formData.username" type="text" required
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
              </div>

              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                <input v-model="formData.password" type="password" required
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
              </div>

              <div>

                <label class="block text-sm font-medium text-gray-700 mb-1">角色</label>

                <select v-model="formData.role_id" required
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                  <option value="20">管理员</option>
                  <option value="10">编辑员</option>
                  <option value="0">普通用户</option>
                </select>
              </div>

              <div>
                <label class="flex items-center">
                  <input v-model="formData.disabled" type="checkbox" class="h-4 w-4 text-blue-600 rounded">
                  <span class="ml-2 text-sm text-gray-700">激活账户</span>
                </label>
              </div>
            </div>

            <div class="mt-6 flex justify-end space-x-3">
              <button type="button" @click="closeModal"
                class="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
                取消
              </button>
              <button type="submit" @click="editorUser()"
                class="px-4 py-2 bg-blue-600 text-white rounded-md text-sm font-medium hover:bg-blue-700">
                {{ isEditing ? '更新' : '添加' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 删除确认对话框 -->
    <div v-if="showDeleteDialog" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-md">
        <div class="p-6">
          <h2 class="text-xl font-semibold mb-4">确认删除</h2>
          <p class="text-gray-600 mb-6">确定要删除用户 "{{ userToDelete?.username }}" 吗？此操作无法撤销。</p>

          <div class="flex justify-end space-x-3">
            <button @click="showDeleteDialog = false"
              class="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
              取消
            </button>
            <button @click="delUser"
              class="px-4 py-2 bg-red-600 text-white rounded-md text-sm font-medium hover:bg-red-700">
              确认删除
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
const { updateUser, getUsers, register, deleteUser } = useUserApi()
import { useResetFormFun } from "../../utils/form"
import adminNavBar from '../../components/admin/admin-nav-bar.vue'

definePageMeta({
  layout: 'minimal',
  showHeader: false
});
// 用户数据
const users = ref([
  // { id: 1, name: '管理员', password: 'admin@example.com', role: 'admin', disabled: true },
  // { id: 2, name: '编辑员', password: 'editor@example.com', role: 'editor', disabled: true },
  // { id: 3, name: '普通用户', password: 'user@example.com', role: 'user', disabled: false }
])

// 角色名称映射
const roleNames = {
  20: '管理员',
  10: '编辑员',
  0: '普通用户'
}

// 搜索和分页
const searchQuery = ref('')
const currentPage = ref(1)
const itemsPerPage = 10

// 模态框状态
const showModal = ref(false)
const showDeleteDialog = ref(false)
const isEditing = ref(false)
const userToDelete = ref(null)
const pagination = ref()


// 表单数据
// const formData = reactive({
//   id: null,
//   name: '',
//   password: '',
//   role: 'user',
//   role_id: 0,
//   disabled: true,
//   disable: 0
// })
const { formData, resetForm, updateForm } = useResetFormFun(() => ({
  id: null,
  name: '',
  password: '',
  role: 'user',
  role_id: 0,
  disabled: true,
  disable: 0
}));
// const resetForm = () => {
//   formData.id = null
//   formData.name = ''
//   formData.password = ''
//   formData.role = 'user'
//   formData.disabled = true
//   formData.disable = 0
// }


// 计算属性
// const filteredUsers = computed(() => {
//   return users.value.filter(user =>
//     user.username.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
//     user.password.toLowerCase().includes(searchQuery.value.toLowerCase())
//   )
// })

const roleClass = (role) => {
  return {
    '20': 'bg-purple-100 text-purple-800', // 管理员
    '10': 'bg-blue-100 text-blue-800', // 编辑员
    '0': 'bg-green-100 text-green-800',// 普通用户
    'undefined': 'bg-green-100 text-green-800' // 普通用户
  }[role] + ' px-2 inline-flex text-xs leading-5 font-semibold rounded-full'
}

const statusClass = (isActive) => {
  return isActive == 0
    ? 'bg-green-100 text-green-800 px-2 inline-flex text-xs leading-5 font-semibold rounded-full'
    : 'bg-red-100 text-red-800 px-2 inline-flex text-xs leading-5 font-semibold rounded-full'
}

// 方法
const openAddModal = () => {
  resetForm()
  console.log('formData openAddModal', formData.value)
  isEditing.value = false
  showModal.value = true
}

const openEditModal = (user) => {
  // Object.assign(formData, user)
  // assign(user) // 重置并覆盖部分字段
  updateForm(user)
  console.log('formData openEditModal', formData.value)

  formData.value.disabled = formData.value.disable ? 0 : 1
  isEditing.value = true
  showModal.value = true
}

const closeModal = () => {
  showModal.value = false
}


const editorUser = async () => {
  try {
    formData.value.disable = formData.value.disabled === 0 ? true : false
    if (!isEditing.value) {
      await register(
        formData.value
      )
    } else {
      await updateUser(
        formData.value
      )
    }

    closeModal()
    resetForm()
    await loadUsers()
  } catch (error) {
    console.error(error)
  }
}

const submitForm = () => {
  if (isEditing.value) {
    // 更新用户
    const index = users.value.findIndex(u => u.id === formData.value.id)
    if (index !== -1) {
      users.value[index] = { ...formData.value }
    }
  } else {
    // 添加新用户
    const newId = Math.max(...users.value.map(u => u.id)) + 1
    users.value.push({
      id: newId,
      ...formData.value
    })
  }
  closeModal()
}

const confirmDelete = (user) => {
  userToDelete.value = user
  showDeleteDialog.value = true
}


const delUser = async () => {
  await deleteUser(userToDelete.value.user_id)
  loadUsers()
  // users.value = users.value.filter(u => u.id !== userToDelete.value.id)
  showDeleteDialog.value = false
}

const nextPage = () => {
  if (currentPage.value * itemsPerPage < users.value.length) {
    currentPage.value++
  }
}

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
  }
}

// 获取用户数据
const loadUsers = async () => {
  try {
    const { data } = await getUsers(1, 10)
    users.value = data?.list || []
    pagination.value = data?.pagination || {}
  } catch (error) {
    console.error('Failed to load users:', error)
  }
}

// 初始化加载
onMounted(() => {
  loadUsers()
  // loading.value = true
  // loadUsers()
  //   .then(() => {
  //     loading.value = false
  //   })
  //   .catch(() => {
  //     loading.value = false
  //   })
})
</script>